package com.book.controller;

import com.book.entity.Account;
import com.book.permission.CheckPermission;
import com.book.service.AccountService;
import com.book.service.MenuService;
import com.book.util.JsonResult;
import com.book.util.JwtUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author SuperYu  2024/7/30
 */

// @CrossOrigin(exposedHeaders = "*")
@RestController
@RequestMapping("/api")
@Slf4j
public class AccountController {
    @Resource
    AccountService accountService;

    @Resource
    JwtUtil jwtUtil;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    MenuService menuService;


    @PostMapping("/login")
    public JsonResult<String> login(String userName, String password, HttpServletResponse response) {
        JsonResult<String> result = new JsonResult<>();

        Account temp = accountService.findAccountByLogin(userName);
        if (temp != null) {
            if (temp.getPassword().equals(password)) {
                log.info("--- 登录成功 ----");

                // 生成一个token
                String token = jwtUtil.createToken(userName);
                log.info("后端生成的token:" + token);

                // 把token存入redis中。。。。
                stringRedisTemplate.opsForValue().set(userName , token, jwtUtil.getExpire(), TimeUnit.MINUTES);
                // 得到当前角色的权限数据，把数据存入redis中
                menuService.findPermissionByUserName(userName);

                response.setHeader("authentication", token);

                result.setStatus(200);
                result.setMessage("登录成功");
            } else {
                result.setStatus(500);
                result.setMessage("密码错误");
            }
        } else {
            result.setStatus(500);
            result.setMessage("用户名错误");
        }

        return result;
    }

    @GetMapping("/account/findBypage")
    public JsonResult<PageInfo<Account>> findByPage(int pageNum, int pageSize) {
        PageInfo<Account> page = accountService.findAccountByPage(pageNum, pageSize);
        return JsonResult.ok(page);
    }

    @GetMapping("/account/del/{id}")
    public JsonResult<String> del(@PathVariable int id) {
        int i = accountService.deleteAccountById(id);
        if (i > 0) {
            return JsonResult.ok(i + "");
        }
        return JsonResult.error(i + "");
    }

    @GetMapping("/order/addOrder")
    @CheckPermission("order:insert")
    public JsonResult<String> order() {

        System.out.println("-新增订单的方法 ----");

        return JsonResult.ok(null);
    }

}













